package com.online_video.service.impl;

import com.online_video.dao.UserDao;
import com.online_video.dao.impl.UserDaoImpl;
import com.online_video.entity.Page;
import com.online_video.entity.User;
import com.online_video.service.UserService;

import java.util.List;

/**
 * @author zhenghouwen
 * @create 2022-03-14 11:57
 */
public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();
    @Override
    public User login(User user) {
        return userDao.queryByUsernameAndPassword(user);
    }

    @Override
    public int register(User user) {
        boolean existsUsername = isExistsUsername(user.getUsername());
        if (!existsUsername){
            return userDao.insert(user);
        }else {
            return -1;
        }
    }

    @Override
    public boolean isExistsUsername(String username) {
        User user = userDao.queryByUsername(username);
        if (user != null){
            return true;
        }
        return false;
    }

    @Override
    public List<User> queryAllUser() {
        return null;
    }

    @Override
    public int deleteUserById(Integer id) {
        return userDao.delete(id);
    }

    @Override
    public Page<User> page(int pageNo, int pageSize) {
        Page<User> page = new Page<>();
        // 设置当前页码
        page.setPageNo(pageNo);
        // 设置每页显示的数量
        page.setPageSize(pageSize);
        // 求总记录数
        Integer pageTotalCount = userDao.queryForPageTotalCount();
        // 设置总记录数
        page.setPageTotalCount(pageTotalCount);
        // 求总页码
        Integer PageTotal = pageTotalCount / pageSize;
        if (pageTotalCount % pageSize > 0){
            PageTotal += 1;
        }
        // 设置总页码
        page.setPageTital(PageTotal);
        // 求当前页数据的开始索引
        int begin = (page.getPageNo() - 1) * pageSize;

        List<User> users = userDao.queryForPageItems(begin, pageSize);

        page.setItems(users);

        return page;

    }

    @Override
    public User queryByU_id(Integer u_id) {
        return userDao.queryByU_Id(u_id);
    }

    @Override
    public int insert(User user) {
        return userDao.insert(user);
    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }

    @Override
    public int updatePwd(String pwd, Integer userId) {
        return userDao.updatePwd(pwd,userId);
    }

}
